var express = require('express')
var router = express.Router()
const { getAll, getById, exec } = require('../db/index')
const jwt = require('jsonwebtoken');
const config = require('../config');
const { createConnection } = require('mysql');

router.post('/',async function(req,res){
  const {username,password} = req.body
  let sql = `select id,password from admins where username='${username}'`
  const data = await exec(sql)
  if(data.length){
    const pass = data[0].password
    // 获取payload
    const payload = {
      id:data[0].id,
      username,
    }
    // 获取密钥
    const secret = config.token.secretKey
    const option = config.token.options
    const token = jwt.sign(payload,secret,option)
    // console.log(password,pass)
    // return
    if(password == pass){
      res.send({
        code:0,
        message:'登录成功',
        token
      })
    }else{
      res.send({
        code:1,
        message:'用户名或密码错误,登录失败',
        token:''
      })
    }
  }else{
    res.send({
      code:1,
      message:'不存在该用户',
      token:''
    })
  }
  
})


module.exports = router